package com.hl.card.credit.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hl.card.credit.domain.CardStatus;
import com.hl.card.credit.domain.CreditCardOrder;
import com.hl.card.credit.domain.CreditCardOrderVo;
import com.hl.card.credit.service.CreditCardOrderService;
import com.hl.card.credit.service.PingAnCreditCardService;
import com.hl.card.credit.service.RabbitMQService;
import com.hl.card.credit.service.remote.RewardReslove;
import com.hl.card.credit.utill.PingAnTool;
import com.hl.card.credit.utill.ResponseObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("card")
public class CreditCardOrderController {

    private static final Logger logger = LoggerFactory.getLogger(CreditCardOrderController.class);

    @Autowired
    private CreditCardOrderService creditCardOrderService;

    @Autowired
    private PingAnCreditCardService pingAnCreditCardService;

    @Value("${cardpack.url}")
    private String cardpackurl;
    @Autowired
    private RewardReslove rewardReslove;
    @Autowired
    private RabbitMQService rabbitMQService;
    @Value("${mcode}")
    private String mcode;
    /**
     * 申请创建订单
     * @param orderVo phone(:phone)
     * @param orderVo userid 用户ID
     * @param orderVo merchantCode 用户ID
     *
     * @return
     */
    @RequestMapping(value = "apply")
    public Object saveOrder(CreditCardOrderVo orderVo, String token){
        Map<String,String> map=new HashMap<>();
    /*    if (!creditCardOrderService.checkToken(token)) {
            map.put("msg", "无效token");
            return map;
        }*/
        if(StringUtils.isEmpty(orderVo.getPhone())){
            map.put("code","0");
            map.put("msg","手机号不能为空");
            return map;
        }
        if(StringUtils.isEmpty(orderVo.getUserid())){
            map.put("code","0");
            map.put("msg","用户id不能为空");
            return map;
        }
        try {
            String seqId= PingAnTool.getSeqId(mcode);
            orderVo.setOrderid(seqId);
            orderVo.setOrderCode(seqId);
            creditCardOrderService.saveVo(orderVo);
            String reqURL=pingAnCreditCardService.getRegUrl(seqId);
            map.put("reqURL",reqURL);
            map.put("code","1");
            map.put("msg","申请通过");
        }catch (Exception ex){
            logger.error(ex.getMessage());
            ex.printStackTrace();
            map.put("reqURL","");
            map.put("code","0");
            map.put("msg","申请错误");
        }
        return map;
    }
    /**
     * 查询信用卡状态
     * @param orderId
     * @return
     */
    @RequestMapping(value ="queryOrder")
    public Object queryOrder(String orderId,String token){
        Map<String,Object> map=new HashMap<>();
       /* if (!creditCardOrderService.checkToken(token)) {
            map.put("msg", "无效token");
            return map;
        }*/
        try {
            CreditCardOrder cco= creditCardOrderService.getSatusByOrderId(orderId);
            if(null==cco){
                map.put("code","2");
                map.put("msg","订单不存在");
                map.put("data",cco);
                return map;
            }
            String orederId=cco.getOrderid();
//            CardStatus cardStatus=new CardStatus();
            CardStatus cardStatus= pingAnCreditCardService.getPortStatus(orederId);//todo 增加is_new_user 的返回值测试
                if(cardStatus==null){
                    //是否在此删除订单
                    map.put("code","3");
                    map.put("msg","未完成信用卡申请信息填写，无效订单");
                    map.put("data",cco);
                    return map;
                }
                if(cardStatus.getActivated()!=null){//激活表示
                    cco.setActivated(cardStatus.getActivated());
                }
                if(cardStatus.getApplicationStatus()!=null){
                    cco.setApplicationstatus(cardStatus.getApplicationStatus());
                }
                if(cardStatus.getApplyCompleted()!=null){
                    cco.setApplycompleted(cardStatus.getApplyCompleted());
                }
                if(cardStatus.getBarCode()!=null){
                    cco.setBarcode(cardStatus.getBarCode());
                }
                if(cardStatus.getFirstUsed()!=null){
                    cco.setFirstused(cardStatus.getFirstUsed());
                }
                if(cardStatus.getIsNewUser()!=null){
                    cco.setIsnew(cardStatus.getIsNewUser());
                }
                Map orderStatus = PingAnTool.getOrderStatus(cco);
                String currentStatus= (String) orderStatus.get("currentStatus");
                Integer status= (Integer)orderStatus.get("status");
                cco.setCurrentstatus(currentStatus);
//                cco.setStatus(status);
//                Integer status=cco.getStatus()==null?0:cco.getStatus();
                //{"data":{"data":{"communityAdmin":40,"userId":100,"recommender":60},"erroCode":0},"erroCode":0}
                Integer isNew=cco.getIsnew();//新卡才奖励
//                isNew= isNew==null?1:isNew;
//                isNew=1;
                if(isNew.equals(1)&&status==2){//审批通过，(核卡)，发送冻结奖励
                    ResponseObject responseObject= (ResponseObject) rewardReslove.commonReward("C",cco.getOrderid(),cco.getRootUserid()==null?"":cco.getRootUserid(),cco.getParentUserid()==null?"":cco.getParentUserid(),cco.getUserid(),"0","manual");
                    System.out.println(JSON.toJSONString(responseObject));
                    if(responseObject.getErroCode().equals(0)){
                        JSONObject ro1= JSONObject.parseObject(responseObject.getData().toString());
                        JSONObject ro2= JSONObject.parseObject(ro1.get("data").toString());
                         String urs=String.valueOf(ro2.get("userId"));
                         String uprs=String.valueOf(ro2.get("recommender"));
                         String urrs=String.valueOf(ro2.get("communityAdmin"));
                         String currency=String.valueOf(ro2.get("currency"));
                        if(!urs.equals("null")){
                            cco.setUseridReward(Integer.parseInt(urs));
                            if(!uprs.equals("null")){
                                cco.setParentUseridReward(Integer.parseInt(uprs));
                            }
                            if(!urrs.equals("null")){
                                  cco.setRootUseridReward(Integer.parseInt(urrs));
                            }
                            if(!currency.equals("null")){
                                cco.setCurrency(currency);
                            }
                        }
                        //奖励发放成功，更新用户关系
                        creditCardOrderService.updateUserRelation(cco.getUserid(),cco.getParentUserid());
                    }
                }
                if(isNew.equals(1)&&status==4){//激活,消息通知解冻奖励
                    if(org.apache.commons.lang3.StringUtils.isEmpty(cco.getCurrency())){
                        //核卡奖励补发
                        ResponseObject responseObject= (ResponseObject) rewardReslove.commonReward("C",cco.getOrderid(),cco.getRootUserid()==null?"":cco.getRootUserid(),cco.getParentUserid()==null?"":cco.getParentUserid(),cco.getUserid(),"0","manual");
                        System.out.println(JSON.toJSONString(responseObject));
                        if(responseObject.getErroCode().equals(0)){
                            JSONObject ro1= JSONObject.parseObject(responseObject.getData().toString());
                            JSONObject ro2= JSONObject.parseObject(ro1.get("data").toString());
                            String urs=String.valueOf(ro2.get("userId"));
                            String uprs=String.valueOf(ro2.get("recommender"));
                            String urrs=String.valueOf(ro2.get("communityAdmin"));
                            String currency=String.valueOf(ro2.get("currency"));
                            if(!urs.equals("null")){
                                cco.setUseridReward(Integer.parseInt(urs));
                                if(!uprs.equals("null")){
                                    cco.setParentUseridReward(Integer.parseInt(uprs));
                                }
                                if(!urrs.equals("null")){
                                    cco.setRootUseridReward(Integer.parseInt(urrs));
                                }
                                if(!currency.equals("null")){
                                    cco.setCurrency(currency);
                                }
                            }
                        }
                        creditCardOrderService.update(cco);
                    }
                    Map<String, String> smap = new HashMap<String, String>();
                    if(null!=cco.getUserid()){
                        smap.put("unfreeze", "manual");
                        smap.put("userId", cco.getUserid());
                        smap.put("mchOrderNo", cco.getOrderid());
                        smap.put("amount", cco.getUseridReward()==null?"0":cco.getUseridReward().toString());
                        smap.put("isFree", "isFree");
                        rabbitMQService.send("queue.notify.mch.unfreeze",smap.toString());
                    }
                    if(null!=cco.getParentUserid()){
                        smap = new HashMap<String, String>();
                        smap.put("unfreeze", "manual");
                        smap.put("userId", cco.getParentUserid());
                        smap.put("mchOrderNo",cco.getOrderid());
                        smap.put("amount", cco.getParentUseridReward()==null?"0":cco.getParentUseridReward().toString());
                        smap.put("isFree", "isFree");
                        rabbitMQService.send("queue.notify.mch.unfreeze",smap.toString());
                    }
                    if(null!=cco.getRootUserid()){
                        smap = new HashMap<String, String>();
                        smap.put("unfreeze", "manual");
                        smap.put("userId", cco.getRootUserid());
                        smap.put("mchOrderNo", cco.getOrderid());
                        smap.put("amount",cco.getRootUseridReward()==null?"0":cco.getRootUseridReward().toString());
                        smap.put("isFree", "isFree");
                        rabbitMQService.send("queue.notify.mch.unfreeze",smap.toString());
                    }
                    System.out.println("信用卡激活奖励发放:" + cco.getOrderid());
                }else if(status==5){//首刷奖励不发
                }
                creditCardOrderService.update(cco);
                map.put("code","1");
                map.put("msg","订单查询成功");
                map.put("data",cco);
        }catch (Exception ex){
            ex.printStackTrace();
            map.put("code","0");
            map.put("msg","审核未通过");
            map.put("data","");
        }
        return map;
    }
    /**
     * 查询用户所有订单列表
     * @param phone
     * @return
     */
    @PostMapping(value = "queryAllOrder")
    public Object queryAllOrder(String phone, String token){
        Map<String,Object> map=new HashMap<>();
      /*  if (!creditCardOrderService.checkToken(token)) {
            map.put("msg", "无效token");
            return map;
        }*/
        try {
        List<CreditCardOrder> list=creditCardOrderService.list(phone);
            map.put("code","1");
            map.put("msg","查询成功并显示所有订单列表");
            map.put("data",list);
        }catch (Exception ex){
            logger.info(ex.getMessage());
            map.put("code","0");
            map.put("msg","你还没有注册！请注册用户");
            map.put("data","");
        }
        return map;
    }
    /**
     * 
     * 查询订单进度(停用☺)
     * @param orderId
     * @return
     */
    @GetMapping(value = "queryOrderrPogress")
    public Object queryOrderrPogress(String orderId,String token){
        Map<String,Object> map=new HashMap<>();
      /*  if (!creditCardOrderService.checkToken(token)) {
            map.put("msg", "无效token");
            return map;
        }*/
        try {
            CardStatus cardStatus = pingAnCreditCardService.getPortStatus(orderId);
        	CreditCardOrder cco= pingAnCreditCardService.getSatusByOrderId(orderId);
        	if(null!=cardStatus&&null!=cco){
                if(cardStatus.getActivated()!=null){
                    cco.setActivated(cardStatus.getActivated());
                }
                if(cardStatus.getApplicationStatus()!=null){
                    cco.setApplicationstatus(cardStatus.getApplicationStatus());
                }
                if(cardStatus.getApplyCompleted()!=null){
                    cco.setApplycompleted(cardStatus.getApplyCompleted());
                }
                if(cardStatus.getBarCode()!=null){
                    cco.setBarcode(cardStatus.getBarCode());
                }
                if(cardStatus.getFirstUsed()!=null){
                    cco.setFirstused(cardStatus.getFirstUsed());
                }
            }
            String currentStatus= (String) PingAnTool.getOrderStatus(cco).get("currentStatus");
            cco.setCurrentstatus(currentStatus);
            creditCardOrderService.update(cco);
            map.put("code","1");
            map.put("msg","审核中");
            map.put("data",cco);
        }catch (Exception ex){
            ex.printStackTrace();
            map.put("code","0");
            map.put("msg","审核未通过");
            map.put("data","");
        }
        return map;
    }
    /**
     * 申请人数
     * @return
     */
    @GetMapping(value = "countApplay")
    public Map countApplay(){
        Map map=new HashMap();
        try{
            long count=creditCardOrderService.countApplayOrder();
            map.put("code","1");
            map.put("msg","查询成功");
            map.put("data",count);
        }catch (Exception ex){
            System.out.println("==查询失败==");
            logger.info(ex.getMessage());
            map.put("code","0");
            map.put("msg","查询失败");
            map.put("data",0);
        }
        return map;
    }
    /**
     * 我推荐的的申请
     * @param userId
     * @return
     */
    @GetMapping(value = "myRecommendApplay")
    public Map myApplay(String userId){
        Map map=new HashMap();
        try{
            Map data=creditCardOrderService.getRecommendApplayOrder(userId);
            map.put("code","1");
            map.put("msg","查询成功");
            map.put("data",data);
        }catch (Exception ex){
            ex.printStackTrace();
            map.put("code","0");
            map.put("msg","查询失败");
            map.put("data","");
        }
        return map;
    }
    /**
     * 我推荐的的申请
     * @param userId
     * @return
     */
    @GetMapping(value = "myRecommendApplayPage")
    public Map myApplay(String userId,int pageNum,int pageSize){
        Map map=new HashMap();
        try{
            Map data=creditCardOrderService.getRecommendApplayOrderPage(userId,pageNum,pageSize);
            map.put("code","1");
            map.put("msg","查询成功");
            map.put("data",data);
        }catch (Exception ex){
            ex.printStackTrace();
            map.put("code","0");
            map.put("msg","查询失败");
            map.put("data","");
        }
        return map;
    }
    @GetMapping(value = "myRecommendApplayInfo")
    public Map myRecommendApplayInfo(String userId){
        Map map=new HashMap();
        try{
            Map data=creditCardOrderService.getRecommendApplayInfo(userId);
            map.put("code","1");
            map.put("msg","查询成功");
            map.put("data",data);
        }catch (Exception ex){
            ex.printStackTrace();
            map.put("code","0");
            map.put("msg","查询失败");
            map.put("data","");
        }
        return map;
    }
    /**
     * 做一个接口 限制每日每个用户只能查询5次，缓存第五次查询或者 5个小时内只能查询一次，接口限流
     * @param userId
     * @param token
     * @return
     */
    @GetMapping(value = "checkOrderStatus")
    public Object checkOrderStatus(String userId,String token){
       Map map=new HashMap();
        try{
            //查询一次
            List<CreditCardOrder> orders= creditCardOrderService.findOrdersByUserId(userId);
            for(CreditCardOrder order:orders){
                this.queryOrder(order.getOrderid(),token);
            }
            map.put("code","1");
            map.put("msg","查询成功");
        }catch (Exception e){
            map.put("code","0");
            map.put("msg","查询失败");
        }
        return map;
    }

    /**
     * 给平安银行回调
     * @param order_id
     * @param sign
     * @param data
     * @param uuid
     * @return
     */
    @GetMapping(value = "synOrderStatus")
    public Object synOrderStatus(String order_id,String sign,String data,String uuid){
        Map map=new HashMap();
        //检测签名正确性
        //得到data里的内容
        CreditCardOrder order=creditCardOrderService.findByOrderId(order_id);
        JSONObject json=JSONObject.parseObject(data);
        String status= (String) json.get("application_status");
        String isNew= (String) json.get("is_new_user");
        String update_time= (String) json.get("update_time");
        Integer intStatus=0;
        if (null != order) {
            switch (status) {
                case "review":intStatus=1
                    ;
                    break;
                case "approved":intStatus=2
                    ;
                    break;
                case "rejected":intStatus=-2
                    ;
                case "mailed":intStatus=3
                    ;
                case "activated":intStatus=4
                    ;
                case "firstUsed":intStatus=5
                    ;
            }
            order.setStatus(intStatus);

            if(intStatus==1){
                order.setIsnew(Integer.parseInt(isNew));
            }

            long lt = new Long(update_time);
            Date date = new Date(lt);
            order.setUpdatetime(date);
            creditCardOrderService.reward(order);
            map.put("code", 1);
        } else {
            map.put("code", 0);
        }
      return map;
    }



}

